import BaseView from "./base-view.js";
import axios from "axios";

import {Event, View} from "electron";
import {mainWindow} from "../main-window.js";

import {electronStore} from "../../vendor/electron-store.js";
import {newUrlCache} from "../../helper/cache.js";
import {OnSourceData, SourceRsp} from "../../type/interfaces.js";
import {searchSession} from "../../service/search-session.js";
import {SessionName} from "../../type/const.js";


export default class SearchView extends BaseView {
  private urlCache = newUrlCache();

  constructor() {
    super()
    searchSession.on("source", this.onSource); //发现资源了
  }

  init() {
    super.init(SessionName.Player);
  }

  get parentView(): View | undefined {
    // return this.playerView.view
    return mainWindow.window?.contentView
  }


  loadURL(url: string) {
    if (!this.view) {
      this.init();
    }
    if (!this.view) return;

    this.view.webContents.stop();
    this.urlCache.clear()
    this.view.webContents.loadURL(url);
    mainWindow.send("search-view-load-url")
  }

  clearUrlCache(){
    this.urlCache.clear()
  }


  onDomReady = () => {
    mainWindow.send("search-view-dom-ready")
  };
  onDidNavigate = (event: unknown, url: string) => {
    console.log("onDidNavigate", url);
    mainWindow.send("view-did-navigate", url)
  };
  onDidNavigateInPage = (event: unknown, url: string) => {
    console.log("onDidNavigateInPage", url);
    mainWindow.send("view-did-navigate-in-page", url);
  };

  onDidFailLoad = (e: Event, code: number, desc: string) => {
    mainWindow.send("search-view-did-fail-load", {code, desc})
  };

  //session请求资源发现
  onSource = async (item: OnSourceData) => {
    const rsp: SourceRsp = { data: "", documentURL: "", title: "", ...item }

    const cacheUrl = this.urlCache.get(item.url);
    if (cacheUrl) {
      return;
    }
    if (!this.matchUrl(item.url)) return
    // 页面中可能会不停请求某个链接，做一下去重处理
    this.urlCache.set(item.url, true);

    rsp.title = this.getPageInfo().title
    rsp.documentURL = this.getPageInfo().url
    try {
      const resp = await axios.get(item.url, {
        headers: item.headers,
        proxy: electronStore.getAxiosProxy()
      })
      if (resp.data.indexOf(".m3u8") == -1) {
        rsp.data = resp.data
        mainWindow.send("search-view-source", rsp);
      }
    } catch (e: any) {
      console.error("处理资源错误", e.message, item.url, item.headers)
    }
  };

  matchUrl(url: string) {
    // http://aa.com/player/ec.php?ddfd.m3u8  这种地址匹配不出，pathname为player/ec.php
    const u = new URL(url);
    //return /\.css/.test(u.pathname);
    return /\.m3u8/.test(u.pathname);
  }

  getPageInfo() {
    if (!this.view) {
      return {
        title: "", url: ""
      }
    }
    return {
      title: this.view.webContents.getTitle(),
      url: this.view.webContents.getURL(),
    };
  }

}

export const searchView = new SearchView();
